/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers.classes;

import classes.Breadcrumbs;
import classes.HibernateUtil;
import dao.QuizAnswersDao;
import dao.QuizDao;
import dao.QuizQuestionsDao;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import models.Answers;
import models.Quizquestion;
import org.hibernate.Hibernate;

/**
 *  This servlet handles the take quiz. it gets a question out of the database and sets it. 
 * This servlet also shows
 * @author Vuong Pham<Vuong.Pham@hva.nl>
 */
public class TakeQuizController extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HibernateUtil hu = new HibernateUtil();
        QuizQuestionsDao qqd = new QuizQuestionsDao(hu.openSession());
        QuizAnswersDao qad = new QuizAnswersDao(hu.openSession());
        long quizid = Long.parseLong(request.getParameter("quizid"));

        ArrayList<Quizquestion> allquestions = (ArrayList<Quizquestion>) qqd.findAllbyQuiz(quizid);

        Quizquestion question = allquestions.get(0);
        HttpSession session = request.getSession();

        if (session.getAttribute("answeredList") != null) {
            ArrayList<Long> list = (ArrayList<Long>) session.getAttribute("answeredList");

            if (list.size() >= allquestions.size()) {
                question = null;

                int counter = 0;
                ArrayList<Answers> ownAnswers = new ArrayList<Answers>();
                ArrayList<Answers> correctAnswers = new ArrayList<Answers>();
                for (Long answer : list) {
                    ownAnswers.add(qad.get(answer));
                    if (qad.get(answer).isCorrect()) {
                        counter++;
                        correctAnswers.add(qad.get(answer));
                    } else {
                        ArrayList<Answers> tempanswers = (ArrayList<Answers>) qad.findAllbyQuestion(qad.get(answer).getQuestion().getId());
                        for (Answers temp : tempanswers) {
                            if (temp.isCorrect()) {
                                correctAnswers.add(temp);
                            }
                        }
                    }
                }


                request.setAttribute("right", counter);
                request.setAttribute("total", list.size());
                request.setAttribute("allquestions", allquestions);
                request.setAttribute("quiz", allquestions.get(0).getQuiz());
                request.setAttribute("ownAnswers", ownAnswers);
                request.setAttribute("correctAnswers", correctAnswers);
                session.setAttribute("answeredList", null);
            } else {
                question = allquestions.get(list.size());
            }
        }

        if (question != null) {
            ArrayList<Answers> answers = (ArrayList<Answers>) qad.findAllbyQuestion(question.getId());

            request.setAttribute("answers", answers);
            request.setAttribute("question", question);
            request.setAttribute("quizsize", allquestions.size());

            hu.close();
            
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Category", "Course catalog"),
                new Breadcrumbs("Course?courseid=" + question.getQuiz().getCourse().getId(), question.getQuiz().getCourse().getName()),
                new Breadcrumbs("ViewQuiz?course=" + question.getQuiz().getCourse().getId(), "Quizzes"),
                new Breadcrumbs("TakeQuiz?quizid=" + question.getQuiz().getName(), question.getQuiz().getName()),
                new Breadcrumbs("", "Question " + question.getOrder())
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
        } else {
            // Breadcrumbs
            Breadcrumbs[] breadcrumbs = {
                new Breadcrumbs("Index", "Home"),
                new Breadcrumbs("Category", "Course catalog")
            };
            request.setAttribute("breadcrumbs", breadcrumbs);
        }
        
        RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/take_quiz.jsp");
        dispatcher.forward(request, response);

    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        long id = Long.parseLong(request.getParameter("correct"));
        long quizid = Long.parseLong(request.getParameter("quiz"));

        ArrayList<Long> answerList;
        if (session.getAttribute("answeredList") != null) {
            answerList = (ArrayList<Long>) session.getAttribute("answeredList");
        } else {
            answerList = new ArrayList<Long>();
        }
        answerList.add(id);



        session.setAttribute("answeredList", answerList);

        response.sendRedirect("TakeQuiz?quizid=" + quizid);
    }
}